<?php
/**
 * Created by PhpStorm.
 * User: serafina
 * Date: 2015/9/23
 * Time: 09:50
 */

function mobile_service_fertilizer_case_list($parameters)
{
    global $user;
    $user_info = _get_user_info($user->uid);
    $query = db_select('fertilizer_case', 'C');
    $query->join('farmer', 'F', 'C.farmer_id=F.farmer_id');
    $query->join('plant', 'P', 'C.plant_id=P.plant_id');
    $query->join('addr', 'A', 'A.addr_id=F.addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    $query->leftJoin('addr', 'A5', 'A.village_id=A5.addr_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A5', 'name', 'village');
    //地址级别查询
    if (!empty($parameters['village'])) {//村落级
        $query->condition('A.village_id', $parameters['village'], '=');
    } else if (!empty($parameters['town'])) {//乡镇级
        $query->condition('A.town_id', $parameters['town'], '=');
    } elseif (!empty($parameters['county'])) {//县级
        $query->condition('A.county_id', $parameters['county'], '=');
    } elseif (!empty($parameters['city'])) {//市级
        $query->condition('A.city_id', $parameters['city'], '=');
    } elseif (!empty($parameters['province'])) {//省级
        $query->condition('A.province_id', $parameters['province'], '=');
    }
    if($user_info['role'] != '农户'){
        if (!user_access('view all fertilizer_case') && user_access('view own fertilizer_case')) {
            $query->condition('C.author_uid', $user->uid, '=');
        }
    }else{
        $query->condition('C.farmer_id', $user->uid, '=');
    }
    $query->fields('C');
    $query->addField('F', 'farmer_name');
    $query->addField('P', 'plant_name');
    $query->orderBy('C.fertilizer_case_id', 'DESC');
    if (!empty($parameters['cursor']) && !empty($parameters['comparator'])) { //游标翻页
        $query->condition('C.fertilizer_case_id', $parameters['cursor'], $parameters['comparator']);
    }
    $query->range(0, 10);

    $results = $query->execute();
    $fertilizer_case_list = [];
    if (!empty($results)) {
        foreach ($results as $result) {
            $fertilizer_case_list[] = $result;
        }
    }
    return ["data" => $fertilizer_case_list];
}

function mobile_service_fertilizer_case_add($parameters)
{
    global $user;
    $module_name = "fertilizer_case";
    $id = !empty($parameters['fertilizer_case_id']) ? $parameters['fertilizer_case_id'] : '';
    $transaction = db_transaction();
    try {
        if (empty($id)) { //add new brand_sales
            if (!user_access('add ' . $module_name)) {
                return ['option' => 0, 'errorNum' => 3];
            }
            $nid = db_insert('fertilizer_case')// Table name no longer needs {}
            ->fields(array(
                'farmer_id' => $parameters['farmer_id'],
                'plant_id' => $parameters['plant_id'],
                'effect_desc' => $parameters['effect_desc'],
                'real_yield' => $parameters['real_yield'],
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->execute();
            for ($i = 0; $i < count($parameters['subfertilizer']); $i++) {
                $fertilizer = $parameters['subfertilizer'][$i];
                $fid = db_insert('fertilizer_case_extra')
                    ->fields(array(
                        'fertilizer_case_id' => $nid,
                        'type' => $fertilizer['type'],
                        'fertilizer_id' => $fertilizer['fertilizer_id'],
                        'fertilization_date' => $fertilizer['fertilization_date'],
                        'fertilization_method' => $fertilizer['fertilization_method'],
                        'fertilizer_quantity' => _empty_2_zero($fertilizer['fertilizer_quantity']),
//                        'comments' => $fertilizer['comments'],
                        'author_uid' => $user->uid,
                        'timestamp' => time(),
                    ))
                    ->execute();
            }
            $result_option = (object)["option" => 1];
            return $result_option;
        } else {
            if (!mobile_user_edit_access($module_name, $module_name . '_id', $id, 'edit own ' . $module_name, 'edit all ' . $module_name)) {
                return ['option' => 0, 'errorNum' => 3];
            }
            $nid = db_update('fertilizer_case')
                ->fields(array(
                    'farmer_id' => $parameters['farmer_id'],
                    'plant_id' => $parameters['plant_id'],
                    'effect_desc' => $parameters['effect_desc'],
                    'real_yield' => $parameters['real_yield'],
                    'timestamp' => time(),))
                ->condition('fertilizer_case_id', $id, '=')
                ->execute();

            for ($i = 0; $i < count($parameters['subfertilizer']); $i++) {
                $fertilizer = $parameters['subfertilizer'][$i];
                if (isset($fertilizer['id']) && !empty($fertilizer['id'])) {
                    continue;
                }
                $fid = db_insert('fertilizer_case_extra')
                    ->fields(array(
                        'fertilizer_case_id' => $id,
                        'type' => $fertilizer['type'],
                        'fertilizer_id' => $fertilizer['fertilizer_id'],
                        'fertilization_date' => $fertilizer['fertilization_date'],
                        'fertilization_method' => $fertilizer['fertilization_method'],
                        'fertilizer_quantity' => _empty_2_zero($fertilizer['fertilizer_quantity']),
//                        'comments' => $fertilizer['comments'],
                        'author_uid' => $user->uid,
                        'timestamp' => time(),
                    ))
                    ->execute();
            }
            $result_option = (object)["option" => 1];
            return $result_option;
        }

    } catch (Exception $e) {
        $transaction->rollback();
        $result_option = (object)["option" => 0, "error" => $e->getMessage()];
        return $result_option;
    }

}
